package com.service.sys.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.config.globalException.BusinessException;
import com.entity.sys.Department;
import com.entity.sys.User;
import com.mapper.sys.DepartmentMapper;
import com.mapper.sys.UserMapper;
import com.service.sys.DepartmentService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author clay
 * @since 2022-02-15
 */
@Service
public class DepartmentServiceImpl extends ServiceImpl<DepartmentMapper, Department> implements DepartmentService {

    @Resource
    private DepartmentMapper departmentMapper;

    @Resource
    private UserMapper userService;

    @Override
    public Department getByPrimaryKey(String id) {
        return departmentMapper.selectById(id);
    }

    /**
     * 为了方便 用户表中直接存储的是名称。未存储id， 修改需要刷一下用户表
     * @param department
     * @return
     */
    @Override
    public int update(Department department) {
        Department oldDepartment = this.getById(department.getId());
        List<User> users = userService.selectList(new QueryWrapper<User>().eq(
                "department_id", oldDepartment.getName()
        ));
        users.forEach(user -> {
            user.setDepartmentId(department.getName());
            userService.updateById(user);
                }
        );
        return departmentMapper.updateById(department);
    }

    @Override
    public int delete(String id) {
        Department department = this.getById(id);
        List<User> users = userService.selectList(new QueryWrapper<User>().eq(
                "department_id", department.getName()
        ));
        if (!CollectionUtil.isEmpty(users)) {
            throw new BusinessException("存在被引用的学部, 无法删除!");
        }
        return departmentMapper.deleteById(id);
    }

    @Override
    public List<Department> select(Department department) {
        QueryWrapper<Department> wrapper = new QueryWrapper<>();
        if (!StringUtils.isEmpty(department.getName())) {
            wrapper.eq(
                    "name", department.getName()
            );
        }
        if (Objects.nonNull(department.getEnabled())) {
            wrapper.eq(
                    "enabled", department.getEnabled()
            );
        }
        return departmentMapper.selectList(wrapper);
    }

}
